package com.leyou.task.schedule;

import com.leyou.common.constants.RocketMQConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.RocketMQConstants.TAGS.SECKILL_BEGIN_TAGS;
import static com.leyou.common.constants.RocketMQConstants.TOPIC.SECKILL_TOPIC_NAME;

/**
 * 生成秒杀页面任务
 */
@Slf4j
@Component
public class GenerateSecKillPageTask {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedissonClient client;

    private String lockName = "ly:seckill:createpage";
    /**
     * 发送生成页面的消息
     * 每分钟生成一次
     */
    @Scheduled(fixedDelay = 60000)
    public void GenerateSecKillPage(){
//        生成Lock对象
        RLock lock = client.getLock(lockName);
        boolean b = false;
//        获取分布式锁
        try {
            b = lock.tryLock(0, 30, TimeUnit.SECONDS);
            if(!b){
                return ;
            }
            //        获取生成秒杀页面的日期
            String date = DateTime.now().toString("yyyy-MM-dd");
            String dest = SECKILL_TOPIC_NAME + ":" + SECKILL_BEGIN_TAGS;
            rocketMQTemplate.convertAndSend(dest,date);
            log.info("发送秒杀页面生成消息，date：{}",date);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(b){
                lock.unlock();
            }
        }
    }
}
